// PluginTreeStore.cs 
// 
//  Copyright © 2009 FreeZzaph
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
// 
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 

using System;
using System.Collections.Generic;
using Gtk;
using LibFreeZzaph;

namespace FreeZzaphGUI
{
	internal class PluginTreeNode
	{
		public IFreeZzaphContentProviderPlugin Plugin { get; set; }
		public CategoryGroup CategoryGroup { get; set; }
		public Category Category { get; set; }
	}
	
	internal class PluginTreeStore : TreeStore
	{	
		public PluginTreeStore(IDictionary<string, IFreeZzaphContentProviderPlugin> plugins)
			: base(typeof(PluginTreeNode))
		{
			// Create plugin nodes
			if (plugins.Count > 0)
			{
				foreach (IFreeZzaphContentProviderPlugin plugin in plugins.Values)
				{
					PluginTreeNode pluginNode = new PluginTreeNode();
					pluginNode.Plugin = plugin;
					TreeIter pluginIter = AppendValues(pluginNode);
					
					// Create category group nodes
					foreach (CategoryGroup group in plugin.CategoryGroups.Values)
					{
						PluginTreeNode categoryGroupNode = new PluginTreeNode();
						categoryGroupNode.Plugin = plugin;
						categoryGroupNode.CategoryGroup = group;
					
						TreeIter groupIter = AppendValues(pluginIter,
							categoryGroupNode);
						
						// Create category nodes
						foreach (Category category in group.Categories.Values)
						{
							PluginTreeNode categoryNode = new PluginTreeNode();
							categoryNode.Plugin = plugin;
							categoryNode.CategoryGroup = group;
							categoryNode.Category = category;
							AppendValues(groupIter,
								categoryNode);
						}
					}
				}
				SetSortFunc(0, CategorySorter);
				SetSortColumnId(0, SortType.Ascending);
			}
			else
			{
				AppendValues(new PluginTreeNode());
			}
		}
		
		public int CategorySorter(TreeModel model, TreeIter tia, TreeIter tib)
		{
			PluginTreeNode nodeA = model.GetValue(tia, 0) as PluginTreeNode;
			PluginTreeNode nodeB = model.GetValue(tib, 0) as PluginTreeNode;
			
			if (nodeA.Category == null || nodeB.Category == null)
				return 0;
			
			return String.Compare(nodeA.Category.Description, nodeB.Category.Description);
		}

	}
}
